package cn.changgou.order.service.impl;

import cn.changgou.entity.Result;
import cn.changgou.goods.feign.SkuFeign;
import cn.changgou.goods.feign.SpuFeign;
import cn.changgou.goods.pojo.Sku;
import cn.changgou.goods.pojo.Spu;
import cn.changgou.order.pojo.OrderItem;
import cn.changgou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;

    // 数据存入到哪台机器的Redis
    @Autowired
    private RedisTemplate redisTemplate;

    /*加入购物车*/
    @Override
    public void add(Long id, Integer num, String username) {
        // 当添加购物车数量<=0时，需要移除该商品信息
        if (num <= 0) {
            // 移除购物车该商品
            redisTemplate.boundHashOps("Cart_" + username).delete(id);
            // 如果此时购物车数量为空，则连购物车一起移除
            Long size = redisTemplate.boundHashOps("Cart_" + username).size();
            if (size == null || size <= 0) {
                redisTemplate.delete("Cart_" + username);
            }
            return;
        }

        // 查询商品的详情
        // 1）查询SKU
        Result<Sku> skuResult = skuFeign.findById(id);
        Sku sku = skuResult.getData();
        // 2）查询SPU
        Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());

        Spu spu = spuResult.getData();
        OrderItem orderItem = createOrderItem(id, num, sku, spu);
        // 将购物车数据存入到Redis：namespace->username
        // key:用户名 field:sku的ID  value:购物车数据(order_item)
        redisTemplate.boundHashOps("Cart_" + username).put(id, orderItem);
    }

    /*创建一个OrderItem对象*/
    private OrderItem createOrderItem(Long id, Integer num, Sku sku, Spu spu) {
        // 将加入的购物车的商品信息封装成OrderItem
        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        orderItem.setSpuId(spu.getId());
        orderItem.setSkuId(id);
        orderItem.setName(sku.getName()); //商品的名称  sku的名称
        orderItem.setPrice(sku.getPrice()); //sku的单价
        orderItem.setNum(num); //购买的数量
        orderItem.setMoney(orderItem.getNum() * orderItem.getPrice()); //单价* 数量
        orderItem.setPayMoney(orderItem.getNum() * orderItem.getPrice()); //单价* 数量
        orderItem.setImage(sku.getImage()); //商品的图片dizhi
        return orderItem;
    }

    @Override
    public List<OrderItem> list(String username) {
        List<OrderItem> orderItemList = redisTemplate.boundHashOps("Cart_" + username).values();
        return orderItemList;
    }
}
